function changeSession() {
    jQuery('#session_id').css('background-image', 'url(../img/message_after.png)')
    jQuery('#friend_id').css('background-image', 'url(../img/friend_before.png)')
    jQuery('#friend_apply').css('background-image', 'url(../img/fri_apply_before.png)')
    jQuery('#friend-list').addClass('hide')
    jQuery('#apply-list').addClass('hide')
    jQuery('#session-list').removeClass('hide')
}

function changeFriend() {
    jQuery('#session_id').css('background-image', 'url(../img/message_before.png)')
    jQuery('#friend_id').css('background-image', 'url(../img/friend_after.png)')
    jQuery('#friend_apply').css('background-image', 'url(../img/fri_apply_before.png)')

    jQuery('#session-list').addClass('hide')
    jQuery('#friend-list').removeClass('hide')
    jQuery('#apply-list').addClass('hide')
}

function changeApply(state) {
    jQuery('#session_id').css('background-image', 'url(../img/message_before.png)')
    jQuery('#friend_id').css('background-image', 'url(../img/friend_before.png)')
    jQuery('#friend_apply').css('background-image', 'url(../img/fri_apply_after.png)')

    jQuery('#session-list').addClass('hide')
    jQuery('#friend-list').addClass('hide')
    jQuery('#apply-list').removeClass('hide')
    if (state == true) {
        getApplyList()
    }
}

function getApplyList() {
    jQuery.ajax({
        url: "apply/get_applies",    //获取该用户尚未处理的验证消息
        type: "get",
        success: function (result) {
            if (result.code == 200) {
                var applyInfo = result.data
                var applyStr = '<p class="explain">以下用户请求添加为您的好友</p>'
                for (var apply of applyInfo) {
                    if (apply.applyReason.length >= 15) {
                        apply.applyReason = apply.applyReason.substring(0, 15) + '...'
                    }
                    applyStr += `<li class="apply-li">
                                    <div class="user-search" apply-id="${apply.applyId}">
                                        <div class="apply-img"><img src="${apply.photo}" alt="apply-img"></div>
                                        <p>${apply.username}</p>
                                        <input type="text" id="reason" value="${apply.applyReason}" disabled />
                                        <button onclick=refuseReq(this)>拒绝</button>
                                        <button onclick=agreeReq(this)>同意</button>
                                    </div>
                                 </li>`
                }
                jQuery('#apply-list').html(applyStr)
                showApplyNum()
            } else {
                alert(result.msg)
            }
        }
    })
}

getApplyList()

//同意好友申请
function agreeReq(element) {
    var $parentDiv = jQuery(element).parent()
    var applyId = $parentDiv.attr('apply-id')
    if (applyId == undefined || applyId == '') {
        alert('参数缺失，请联系管理员！')
        return
    }
    jQuery.ajax({
        url: "apply/agree",
        type: "post",
        data: {
            "applyId": applyId
        },
        success: function (result) {
            if (result.code == 200) {
                $parentDiv.parent().remove()    //删除当前的验证消息
                showApplyNum()  //重新计数
                getFriendList() //重新加载好友列表
            } else {
                alert(result.msg)
            }
        }
    })
}


//拒绝好友申请
function refuseReq(element) {
    var applyId = jQuery(element).parent().attr('apply-id')
    if (applyId == undefined || applyId == '') {
        alert('参数缺失，请联系管理员！')
        return
    }
    if (window.confirm('确认拒绝吗？')) {
        jQuery.ajax({
            url: "apply/refuse",
            type: "post",
            data: {
                "applyId": applyId
            },
            success: function (result) {
                if (result.code == 200) {
                    $parentDiv.parent().remove()    //删除当前的验证消息
                    showApplyNum()  //重新计数
                } else {
                    alert(result.msg)
                }
            }
        })
    }
}

function showApplyNum() {
    var num = jQuery('#apply-list li').size()
    if (num == 0) {
        jQuery('.label #apply-num').addClass('hide')
    } else {
        jQuery('.label #apply-num').removeClass('hide')
    }
    jQuery('#apply-num').text((`(待处理${num})`))
}


function scrollToBottom(element) {
    var clientHeight = element.offsetHeight
    var scrollHeight = element.scrollHeight
    element.scrollTo(0, scrollHeight - clientHeight)
}

function getSessionById(sessionId) {
    var lis = document.querySelectorAll('#session-list>li')
    for (var session of lis) {
        if (session.getAttribute('session-id') == sessionId) {
            return session
        }
    }
    return null
}

var webSocket = new WebSocket('ws://127.0.0.1:8080/ws_message')

webSocket.onopen = function () {
    console.log("socket连接建立")
}
webSocket.onmessage = function (e) {
    console.log('接收到消息：' + e.data)
    //先将接收到的字符串消息转换成一个js对象
    var responseData = JSON.parse(e.data)
    if (responseData.messType == "apply") {
        getApplyList()
        return
    }
    //先判断会话在用户的会话列表中是否存在，如果存在则将其置顶；不存在则创建并置顶。在消息的预览区域设置用户昵称和消息预览
    //获取sessionList父元素，方便后续子元素的置顶
    var sessionList = document.querySelector('#session-list')
    var sessionLi = getSessionById(responseData.sessionId)
    if (sessionLi == null) {
        //会话在页面上不存在,手动创建一个
        sessionLi = document.createElement('li')
        jQuery(sessionLi).attr('session-id', responseData.sessionId)
        var content = null

        if (responseData.messType == 'file') {
            content = responseData.originalFileName.length >= 5 ? responseData.originalFileName.substring(0, 5) + '...' : responseData.originalFileName
        } else {
            content = responseData.messContent.length >= 5 ? responseData.messContent.substring(0, 5) + '...' : responseData.messContent
        }
        var slStr = `
                    <div class="session-photo"><img src="${responseData.friendPhoto}" alt="u-img"></div>
                    <div><h3 username=${responseData.username} >${responseData.nickname}</h3>
                    <p>${content}</p></div>
                    <p class="did_num"></p>
                    <p class="send_time">${responseData.createTime}</p>
                `
        jQuery(sessionLi).html(slStr)
    }
    // sessionLi.setAttribute('session-id', responseData.sessionId)
    // sessionLi.innerHTML = `<h3>${responseData.nickname}</h3>
    //                 <p>${responseData.messContent}</p>`
    // let h3InLi = sessionLi.querySelector('h3')
    // // h3InLi.setAttribute('username', responseData.username)
    // sessionList.insertBefore(sessionLi, sessionList.children[0])
    // sessionLi.addEventListener('click', loadDetail($(sessionLi)))
    //将当前li元素置顶

    sessionList.insertBefore(sessionLi, sessionList.children[0])
    var preview = null
    if (responseData.messType == 'file') {
        preview = responseData.originalFileName.length >= 5 ? responseData.originalFileName.substring(0, 5) + '...' : responseData.originalFileName
    } else {
        preview = responseData.messContent.length >= 5 ? responseData.messContent.substring(0, 5) + '...' : responseData.messContent
    }
    jQuery(sessionLi).find('div p').text(preview)

    //判断当前的会话是否为选中状态，如果是，则在消息详情页添加接收到的消息
    if (sessionLi.className == 'selected') {
        // 重新查询一次数据库信息(错误！！)，可能消息还没有添加到数据库中
        //还是在前端页面手动创建吧
        var messageBox = document.createElement('div')
        var itOrSelf = jQuery('#username').attr('user-id') == responseData.fromUId ? "message-self" : "message-it"
        var imgItOrSelf = jQuery('#username').attr('user-id') == responseData.fromUId ? "detail-img-self" : "detail-img"
        var src
        if (imgItOrSelf == 'detail-img') {
            //不是我的头像
            src = responseData.friendPhoto
        } else {
            src = jQuery('.main-box .left-container .userinfo img').attr('src')
        }
        var divInner = null
        if (responseData.messType == 'file') {
            divInner = `<div class="message-box ${itOrSelf} file-type">
            <div class=${imgItOrSelf}><img src="${src}" alt="u-img"></div>
            <div class="message-detail">
                <h3>${responseData.nickname}</h3>
                <p download-path=${responseData.messContent} onclick=downloadFile(this)>
                    <img src="./img/upload_file.png" alt=""><span>${responseData.originalFileName}</span>
                </p>
            </div>
        </div>`
        } else {
            divInner = `<div class="message-box ${itOrSelf}">
            <div class="${imgItOrSelf}"><img src="${src}" alt="u-img"></div>
            <div class="message-detail">
                <h3>${responseData.nickname}</h3>
                <p>${responseData.messContent}</p>
            </div>
        </div>`
        }
        jQuery(messageBox).html(divInner)
        document.querySelector('#mess_detail').appendChild(messageBox)
        scrollToBottom(document.querySelector('#mess_detail'))
        jQuery(sessionLi).find('.did_num').text('未读0')
        //如果当前会话被选中，并且不是当前发送消息的用户
        if (responseData.fromUId != jQuery('#username').attr('user-id')) {
            updateReadState(jQuery(sessionLi))  //更新未读消息状态
        }
    } else {
        //TODO： 判断当前是不是自己再来判断显示消息与否
        //在会话上显示出未读消息的条数
        if (responseData.fromUId == jQuery('#username').attr('user-id')) {
            jQuery(sessionLi).find('.did_num').text('未读0')
            changeActive()
            jQuery(sessionLi).addClass('selected')
        } else {
            showDidNotNum(jQuery(sessionLi))
        }
    }
}




//将会话中未读消息的数量置为0
//可能发生在：用户点击会话时、会话处在被选中状态时....
function updateReadState($sessionLi) {
    jQuery.ajax({
        url: "message/update_state",
        type: "post",
        data: {
            "sessionId": $sessionLi.attr('session-id')
        },
        success: function (result) {
            if (result.code == 200) {
                $sessionLi.find('.did_num').text('未读0')
            }
        }
    })
}


//显示会话上未读的消息条数
function showDidNotNum($sessionLi) {
    jQuery.ajax({
        url: "message/get_dn_num",
        type: "get",
        data: {
            "sessionId": $sessionLi.attr('session-id')
        },
        success: function (result) {
            if (result.code == 200) {
                $sessionLi.find('.did_num').text('未读' + result.data)
            }
        }
    })
}
webSocket.onclose = function () {
    ('socket连接关闭')
}
webSocket.onerror = function () {
    console.log('连接异常')
}


function initSendBtn() {
    jQuery('.right-container .send button').click(() => {
        //获取输入的文本内容
        var $inputEnter = jQuery('#input-enter')
        if ($inputEnter.val() == '') {
            $inputEnter.focus()
            return
        }
        //获取session_id
        var $session = jQuery('.left-container .list .selected')
        if ($session == null) {
            return
        }
        //发送websocket请求
        var requestObj = {
            "sessionId": $session.attr('session-id'),
            "messContent": $inputEnter.val()
        }
        webSocket.send(JSON.stringify(requestObj))
        $inputEnter.val('')
        $inputEnter.focus()
    })
}

initSendBtn()

function getUserInfo() {
    jQuery.ajax({
        url: "user/info",
        type: "get",
        success: function (result) {
            if (result.code == 200) {
                jQuery('#username').text(result.data.username)
                jQuery('#username').attr('user-id', result.data.uId)
                jQuery('.left-container .userinfo img').attr('src', result.data.photo)
            } else {
                alert(result.msg)
                location.href = '../login.html'
            }
        }
    })
}

getUserInfo()


function getFriendList() {
    jQuery.ajax({
        url: "friend/list",
        type: "get",
        success: function (result) {
            if (result.code == 200) {
                var $fList = jQuery('#friend-list')
                var fStr = ''
                for (var friend of result.data) {
                    fStr += `<li to_u_id=${friend.fId}>
                                <div class="s-img"><img src="${friend.friendPhoto}" alt=""></div>
                                <h3 username='${friend.friendName}' >${friend.friendNickname}</h3>
                            </li>`
                }
                $fList.html(fStr)
                $("#friend-list li").each(function () {
                    $(this).click(function () {
                        //TODO: 遍历会话列表，看会话列表中是否有这个用户的信息
                        changeSession()
                        //-----------------------------------
                        var session = getSession($(this).find('h3').attr('username'))
                        if (session != null) {
                            //session已经在当前用户的会话列表中存在了
                            changeActive()
                            var sessions = document.querySelector('#session-list')
                            sessions.insertBefore(session, sessions.firstChild)
                            $(session).addClass('selected')
                            var sessionLi = getSession($(this).find('h3').attr('username'))
                            loadDetail($(sessionLi))
                        } else {
                            //session在当前用户的会话列表中不存在
                            //1.请求后端接口，创建会话信息
                            //2.置顶并高亮
                            var toUId = $(this).attr('to_u_id')
                            if (toUId == '' || toUId == undefined || toUId == null) {
                                alert("参数非法！无法建立会话！")
                                return
                            }
                            var username = $(this).find('h3').attr('username')

                            jQuery.ajax({
                                url: "session/add",
                                type: "post",
                                data: {
                                    "toUId": toUId
                                },
                                success: function (result) {
                                    if (result.code == 200) {
                                        getMessageList(true, username)
                                    } else {
                                        alert(result.msg)
                                    }
                                }
                            })
                        }
                    })
                })
            } else {
                alert(result.msg)
            }
        }
    })
}

getFriendList()

function changeActive() {
    var lis = jQuery('#session-list li')
    lis.removeClass('selected')
}


function getMessageList(istransfer, username) {
    jQuery.ajax({
        url: "session/list",
        type: "get",
        async: "false",
        success: function (result) {
            if (result.code == 200) {
                var $slist = jQuery('#session-list')
                var sStr = ``
                for (var message of result.data) {
                    var friendNickName = message.friendInfoVOS[0].friendNickname
                    if (friendNickName.length > 5) {
                        friendNickName = friendNickName.substring(0, 5) + '...'
                    }
                    sStr += `<li session-id=${message.sessionId}>
                               <div class="session-photo"><img src="${message.friendInfoVOS[0].friendPhoto}" alt="u-img"></div>
                                <div><h3 username=${message.friendInfoVOS[0].friendName} >${friendNickName}</h3>
                                <p>${message.lastMessage}</p></div>
                                <p class="did_num">未读${message.didNotNum}</p>
                                <p class="send_time">${message.updateTime}</p>
                            </li>`
                }
                $slist.html(sStr)
                $("#session-list li").each(function () {
                    $(this).click(function () {
                        changeActive()
                        $(this).addClass('selected')
                        loadDetail($(this))
                        updateReadState($(this)) //将消息状态置为已读
                        //将当前会话置顶
                        // var sessionList = document.querySelector('#session-list')
                        // sessionList.insertBefore($(this)[0], sessionList.children[0])
                    });
                });
                if (istransfer) {
                    $(document.querySelector('#session-list').firstChild).addClass('selected')
                    loadDetail($(getSession(username)))
                }
            } else {
                alert(result.msg)
                location.href = '../login.html'
            }
        }
    })
}

getMessageList()


function getSession(username) {
    var lis = document.querySelectorAll('#session-list>li')
    for (var i = 0; i < lis.length; i++) {
        var li = lis[i]
        if ($(li).find('h3').attr('username') == username) {
            return li
        }
    }
    return null
}


function loadDetail($li) {
    jQuery.ajax({
        url: "message/detail",
        type: "get",
        data: {
            "sessionId": $li.attr('session-id')
        },
        success: function (result) {
            if (result.code == 200) {
                var detailStr = ''
                jQuery('#userNick').html($li.find('h3').text())
                var $messDetail = jQuery('#mess_detail')
                for (var messageDetail of result.data) {
                    var itOrSelf = jQuery('#username').attr('user-id') == messageDetail.fromUId ? "message-self" : "message-it"
                    var imgItOrSelf = jQuery('#username').attr('user-id') == messageDetail.fromUId ? "detail-img-self" : "detail-img"
                    var src
                    if (imgItOrSelf == 'detail-img') {
                        src = $li.find('img').attr('src')
                    } else {
                        src = jQuery('.main-box .left-container .userinfo img').attr('src')
                    }
                    // console.log(itOrSelf)
                    if (messageDetail.messType == 'file') {
                        detailStr += `<div class="message-box ${itOrSelf} file-type">
                        <div class=${imgItOrSelf}><img src="${src}" alt="u-img"></div>
                        <div class="message-detail">
                            <h3>${messageDetail.nickname}</h3>
                            <p download-path=${messageDetail.messContent} onclick=downloadFile(this)>
                                <img src="./img/upload_file.png" alt=""><span>${messageDetail.originalFileName}</span>
                            </p>
                        </div>
                    </div>`
                    } else {
                        detailStr += `<div class='message-box ${itOrSelf}'>
                                        <div class="${imgItOrSelf}"><img src="${src}" alt="u-img"></div>
                                        <div class='message-detail'>
                                            <h3>${messageDetail.nickname}</h3>
                                            <p>${messageDetail.messContent}</p>
                                        </div>
                                 </div>`
                    }
                }
                $messDetail.html(detailStr)
                scrollToBottom(document.querySelector('#mess_detail'))  //滚动消息显示页面到最底部
            } else {
                alert(result.msg)
            }
        }
    })
}


function sendSearchReq() {
    var $searchIpt = jQuery('.left-container .search input')
    if ($searchIpt.val() == '') {
        $searchIpt.focus()
        return
    }
    jQuery.ajax({
        url: "user/get_users",  //按照用户名查找用户
        type: "get",
        data: {
            "username": $searchIpt.val()
        },
        success: function (result) {
            if (result.code == 200) {
                var users = result.data
                var $applyList = jQuery('#apply-list')
                var listStr = ''
                for (var user of users) {
                    if (user.isAdded == 1) { //该好友已添加
                        listStr += `<li><div class="user-search">
                                    <div class="a-img"><img src="${user.photo}" alt="a-img"></div>
                                    <p user-id=${user.uId}>${user.username}</p>
                                    <button class="added">已添加</button>
                                </div></li>`
                    } else {
                        listStr += `<li><div class="user-search">
                                    <div class="a-img"><img src="${user.photo}" alt="a-img"></div>
                                    <p user-id=${user.uId}>${user.username}</p>
                                    <button onclick="playApply(this)">申请</button>
                                </div></li>`
                    }
                }
                if (listStr == '') {
                    listStr = `<p id="null-user">未搜索到！<p>`
                }
                $applyList.html(listStr)
                changeApply(false)  //不跳转好友请求
            } else {
                alert(result.msg)
            }
        }

    })
}

function closeApplyContainer() {
    jQuery('.apply-container').addClass('hide')
}


function playApply(btnElem) {
    var $prevP = jQuery(btnElem).prev()
    jQuery('.apply-container').removeClass('hide')
    jQuery('.apply-container .apply-detail #apply-reason').attr('user-id', $prevP.attr('user-id'))
}



function sendAddReq() {
    $applyReason = jQuery('.apply-container .apply-detail #apply-reason')
    if ($applyReason.val() == '') {
        alert('请先输入申请原因！')
        $applyReason.focus()
        return
    }
    if ($applyReason.attr('user-id') == undefined) {
        alert("400,请联系管理员！")
        return
    }

    jQuery.ajax({
        url: "apply/add",
        type: "post",
        data: {
            "toUId": $applyReason.attr('user-id'),
            "applyReason": $applyReason.val()
        },
        success: function (result) {
            if (result.code == 200) {
                alert('发送成功，请等待对方同意！')
                closeApplyContainer()
            } else {
                alert(result.msg)
            }
        }
    })
}

//前端上传文件的实现

//1.给img标签绑定点击事件，当其点击的时候就模拟点击file上传文本框
jQuery('.right-container .fun-list .upload-file img').click(() => {
    jQuery('.right-container .fun-list .upload-file #selected-file').click()
})

/**
 * 完成发送文件的功能
 */
function uploadFile($iptFile, sendPath) {
    if ($iptFile.val() == '') {
        return
    }
    var formData = new FormData()
    formData.append("fileData", $iptFile[0].files[0])
    var $session = jQuery('.left-container .list .selected')
    if ($session == null || $session.attr('session-id') == undefined) {
        return
    }
    formData.append('sessionId', $session.attr('session-id'))
    jQuery.ajax({
        url: sendPath,
        type: 'post',
        data: formData,
        contentType: false,
        processData: false,
        success: function (result) {
            if (result.msg != '') {
                alert('发送文件失败，请稍后重试！')
            }
        }
    })
}

//给文件上传文本框绑定change事件，文件上传后自动发送
jQuery('.right-container .fun-list .upload-file #selected-file').change(() => {
    //接着写文件的发送逻辑
    uploadFile(jQuery('.right-container .fun-list .upload-file #selected-file'), 'message/up_file')
})


//为message-list中的file-type中的p绑定点击事件
function downloadFile(p) {
    var downloadPath = jQuery(p).attr('download-path')
    window.open("/files/down?filename=" + downloadPath.substring(5))
}